/*
 * P2PScrabbleView.java
 */

package p2pscrabble;

import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.WindowConstants;

/**
 * The application's main frame.
 */
public class MainWindow extends JFrame implements ActionListener {

	// Variables declaration
	private final javax.swing.JPanel actionPanel;
	private final javax.swing.JButton undoButton;
	private final javax.swing.JPanel mainPanel;
	private final javax.swing.JButton passButton;
	private final javax.swing.JButton submitButton;
	private final javax.swing.JButton swapButton;
	private final javax.swing.JButton clearButton;
	private final TimerPanel timerPanel;
	private final PlayerScorePanel scorePanel;
	private final GamePanel gamePanel;
	private final MenuBar menuBar;
	private final Game game;
	private final ChatPanel chatPanel;
	private final WordChecker wordChecker;

	int playerTurn = 0;

	// End of variables declaration

	public MainWindow(final Game game) {

		this.game = game;

		mainPanel = new javax.swing.JPanel();
		scorePanel = new PlayerScorePanel(game.player1, game.player2, game
				.isMyTurn(), game.amIPlayer1());
		gamePanel = new GamePanel(game.getBag());
		actionPanel = new javax.swing.JPanel();
		submitButton = new javax.swing.JButton();
		swapButton = new javax.swing.JButton();
		passButton = new javax.swing.JButton();
		clearButton = new javax.swing.JButton();
		undoButton = new javax.swing.JButton();
		timerPanel = new TimerPanel(game.isMyTurn(), game.amIPlayer1());
		menuBar = new MenuBar(game);
		chatPanel = new ChatPanel(game);
		wordChecker = new WordChecker();

		playerTurn = (game.isMyTurn() && game.amIPlayer1())
				|| (!game.isMyTurn() && !game.amIPlayer1()) ? 0 : 1;

		initComponent();

		// action button
		submitButton.setText("Submit");
		swapButton.setText("Swap");
		passButton.setText("Pass");
		clearButton.setText("Clear");
		undoButton.setText("Undo");

		// command
		submitButton.setActionCommand("submit");
		submitButton.addActionListener(this);
		swapButton.setActionCommand("swap");
		swapButton.addActionListener(this);
		passButton.setActionCommand("pass");
		passButton.addActionListener(this);
		clearButton.setActionCommand("clear");
		clearButton.addActionListener(this);
		undoButton.setActionCommand("undo_request");
		undoButton.addActionListener(this);

		final Container c = this.getContentPane();
		this.setJMenuBar(menuBar);
		c.add(mainPanel);
		this.setTitle("P2P Scrabble by Freddy");

		this.addWindowListener(new java.awt.event.WindowAdapter() {
			public void windowClosing(final java.awt.event.WindowEvent evt) {
				menuBar.exit_action(null);
			}
		});
		this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
	}// </editor-fold>

	@Override
	public void actionPerformed(final ActionEvent arg0) {
		// TODO Auto-generated method stub
		if (arg0.getActionCommand().equals("submit")) {
			submit_action(true);
		}
		if (arg0.getActionCommand().equals("swap")) {
			swap_action(true);
		}
		if (arg0.getActionCommand().equals("pass")) {
			pass_action(true);
		}
		if (arg0.getActionCommand().equals("clear")) {
			clearBoard();
		}
		if (arg0.getActionCommand().equals("undo_request")) {
			undo_request_action();
		}
	}

	public void submit_action(boolean inform) {
		if (!gamePanel.checkValidSubmit())
			return;
		String words_and_score = gamePanel.submitWords();

		String wrongWords = game.checkWords(words_and_score);
		if (!wrongWords.equals("")) {
			new InfoWindow(1, "Error", "Invalid words:"
					+ wrongWords);
			System.out.println("One of the words is not valid");
			return;
		}

		String split[] = words_and_score.split(";");
		scorePanel.addScore(playerTurn, Integer.parseInt(split[0]));

		// inform other player
		if (inform) {
			game.submit(split[1], gamePanel.getCurBoardLetter(), Integer
					.parseInt(split[0]), gamePanel.drawTiles());
		}
		gamePanel.setFirstTurn(false);
		gamePanel.finish_submit();
	}

	public void swap_action(boolean swap) {
		if (swap) {
			if (!gamePanel.swapLetters())
				return;
			game.swap(gamePanel.drawTiles());
		}
	}

	public void pass_action(boolean notify) {
		clearBoard();

		if (notify) {
			game.pass();
		}
	}

	public void clearBoard() {
		char[] letters = game.amIPlayer1() ? game.getNowState()
				.getPlayer1Letter() : game.getNowState().getPlayer2Letter();
		gamePanel.clearBoard(game.getNowState().getBoardLetter(), letters);
	}

	public long getMyTime() {
		return timerPanel.getMyRemaining();
	}

	public void setTimer(long oppTime) {
		timerPanel.setOppTimer(oppTime);
	}

	public void appendChatMessage(String s) {
		chatPanel.appendMessage(s, false);
	}

	public void undo_request_action() {
		game.undo_request();
	}

	public void setScore(int player1Score, int player2Score) {
		scorePanel.setScore(player1Score, player2Score);
	}

	public void setTiles(char[][] boardLetters, char[] myLetters) {
		gamePanel.setTiles(boardLetters, myLetters);
	}

	public void updateMainWindowView(boolean b) {
		submitButton.setEnabled(b);
		swapButton.setEnabled(b);
		gamePanel.setBoardEnabled(b);

		playerTurn = (game.isMyTurn() && game.amIPlayer1())
				|| (!game.isMyTurn() && !game.amIPlayer1()) ? 0 : 1;

		scorePanel.setTurn(playerTurn);
		timerPanel.setTurn(playerTurn);
	}

	public void submitOppTiles(char[] letters, int[] row, int[] col) {
		gamePanel.submitOppTiles(letters, row, col);
	}

	private void initComponent() {
		scorePanel.setBorder(javax.swing.BorderFactory.createEtchedBorder(null,
				Color.BLUE));

		final javax.swing.GroupLayout scorePanelLayout = new javax.swing.GroupLayout(
				scorePanel);
		scorePanel.setLayout(scorePanelLayout);
		scorePanelLayout.setHorizontalGroup(scorePanelLayout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGap(0, 150, Short.MAX_VALUE));
		scorePanelLayout.setVerticalGroup(scorePanelLayout.createParallelGroup(
				javax.swing.GroupLayout.Alignment.LEADING).addGap(0, 100,
				Short.MAX_VALUE));

		final javax.swing.GroupLayout actionPanelLayout = new javax.swing.GroupLayout(
				actionPanel);
		actionPanel.setLayout(actionPanelLayout);
		actionPanelLayout
				.setHorizontalGroup(actionPanelLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								javax.swing.GroupLayout.Alignment.TRAILING,
								actionPanelLayout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												actionPanelLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(
																undoButton,
																javax.swing.GroupLayout.Alignment.LEADING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																79,
																Short.MAX_VALUE)
														.addComponent(
																submitButton,
																javax.swing.GroupLayout.Alignment.LEADING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																79,
																Short.MAX_VALUE)
														.addComponent(
																swapButton,
																javax.swing.GroupLayout.Alignment.LEADING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																79,
																Short.MAX_VALUE)
														.addComponent(
																clearButton,
																javax.swing.GroupLayout.Alignment.LEADING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																79,
																Short.MAX_VALUE)
														.addComponent(
																passButton,
																javax.swing.GroupLayout.Alignment.LEADING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																79,
																Short.MAX_VALUE))
										.addGap(60, 60, 60)));
		actionPanelLayout
				.setVerticalGroup(actionPanelLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								actionPanelLayout
										.createSequentialGroup()
										.addContainerGap()
										.addComponent(submitButton)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(swapButton)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(clearButton)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(passButton)
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(undoButton)
										.addContainerGap(131, Short.MAX_VALUE)));

		// layout
		final javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(
				mainPanel);

		mainPanel.setLayout(mainPanelLayout);
		mainPanelLayout
				.setHorizontalGroup(mainPanelLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								mainPanelLayout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												mainPanelLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																actionPanel,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																Short.MAX_VALUE)
														.addComponent(
																timerPanel,
																javax.swing.GroupLayout.PREFERRED_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.PREFERRED_SIZE)
														.addComponent(
																scorePanel,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																Short.MAX_VALUE)
														.addComponent(
																wordChecker,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																Short.MAX_VALUE)
														.addComponent(
																chatPanel,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																Short.MAX_VALUE))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.RELATED)
										.addComponent(
												gamePanel,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												450,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addContainerGap()));

		mainPanelLayout
				.setVerticalGroup(mainPanelLayout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								mainPanelLayout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												mainPanelLayout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.TRAILING)
														.addComponent(
																gamePanel,
																javax.swing.GroupLayout.Alignment.LEADING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																468,
																Short.MAX_VALUE)
														.addGroup(
																javax.swing.GroupLayout.Alignment.LEADING,
																mainPanelLayout
																		.createSequentialGroup()
																		.addComponent(
																				timerPanel,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				scorePanel,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				actionPanel,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				Short.MAX_VALUE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)
																		.addComponent(
																				wordChecker,
																				50,
																				50,
																				Short.MAX_VALUE)
																		.addPreferredGap(
																				javax.swing.LayoutStyle.ComponentPlacement.RELATED)

																		.addComponent(
																				chatPanel,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				Short.MAX_VALUE)))
										.addGap(15, 15, 15)));

	}
}
